package com.dd.controller;

import com.dd.entity.Book;
import com.dd.entity.R;
import com.dd.enums.HttpEnum;
import com.dd.service.BookService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 书籍控制器
 */
@RestController
@RequestMapping("/books")
@CrossOrigin
public class BookController {

    @Autowired
    BookService bookService;

    //获取全部书籍信息  作者/书籍名称
    @GetMapping
    public List<Book> getList(String bookName,String author){

        return bookService.getList(bookName,author);
    }

    @GetMapping("/page")
    public R<PageInfo<Book>> getPage(String bookName, String author, Integer pageNum){
        PageInfo<Book> pageBooks = bookService.getPage(bookName,author,pageNum);

        return R.success(pageBooks);
//        return R.fail(HttpEnum.ERROR.getCode(), "查询失败");
    }

    //获取书籍详情
    @GetMapping("/{id}")
    public R<Book> getBookDetail(@PathVariable Integer id){
        return R.success(bookService.getBookDetail(id));
    }

    //新增书籍
    @PostMapping
    public R saveBook(@RequestBody @Valid Book book){

//        if (StringUtils.isEmpty(book.getBookName())){
//            return R.fail(HttpEnum.VALIDATE_ERROR.getCode(), "书籍名称不能为空");
//        }
//        //验证作者
//        if (StringUtils.isBlank(book.getAuthor())){
//            return R.fail(HttpEnum.VALIDATE_ERROR.getCode(), "作者不能为空");
//        }

        int count = bookService.saveBook(book);
        return count > 0 ? R.success("新增成功") : R.fail(HttpEnum.ERROR.getCode(), "新增失败");
    }

    //修改书籍
    @PutMapping
    public String updateBook(@RequestBody Book book){
        int count = bookService.updateBook(book);
        return count > 0 ? "修改成功" : "修改失败";
    }


    //删除书籍
    @DeleteMapping("/{id}")
    public String deleteBook(@PathVariable Integer id){
        int count = bookService.deleteBook(id);
        return count > 0 ? "删除成功" : "删除失败";
    }

}
